﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using Core.Common;

namespace DataReceiver.DataAPI
{
    public class Bson_Tick : Model_Tick
    {
        public BsonObjectId _id;
    }

    public class MongoOperater
    {
        public static void InsertTicks(List<Model_Tick> ticks)
        {
            try
            {
                //创建数据连接
                MongoClient client = new MongoClient(ConfigHelper.MongoDBConnectionstring);
                MongoServer server = client.GetServer();
                //获取指定数据库
                MongoDatabase db = server.GetDatabase("Futures");
                //获取表
                MongoCollection col = db.GetCollection("Ticks");
                //插入数据
                col.InsertBatch(ticks);
                //关闭连接
                server.Disconnect();
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLine("插入数据错误：" + ex.Message);
            }
        }

        public static List<Bson_Tick> FindTicks(int amount)
        {
            List<Bson_Tick> resualt = new List<Bson_Tick>();
            try
            {
                //创建数据连接
                MongoClient client = new MongoClient(ConfigHelper.MongoDBConnectionstring);
                MongoServer server = client.GetServer();
                //获取指定数据库
                MongoDatabase db = server.GetDatabase("Futures");
                //获取表
                MongoCollection col = db.GetCollection("Ticks");
                //查询数据
                resualt = col.FindAllAs<Bson_Tick>().SetLimit(amount).ToList<Bson_Tick>();
                //关闭连接
                server.Disconnect();
                return resualt;
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLine("获取数据错误：" + ex.Message);
                return resualt;
            }
        }

        public static bool RemoveTicks(List<Bson_Tick> ticks)
        {
            try
            {
                //创建数据连接
                MongoClient client = new MongoClient(ConfigHelper.MongoDBConnectionstring);
                MongoServer server = client.GetServer();
                //获取指定数据库
                MongoDatabase db = server.GetDatabase("Futures");
                //获取表
                MongoCollection col = db.GetCollection("Ticks");
                //查询数据
                var query = Query.In("_id", ticks.Select(x => x._id));
                col.Remove(query);
                //关闭连接
                server.Disconnect();
                return true;
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLine("删除数据失败：" + ex.Message);
                return false;
            }
        }
    }
}
